<?php

namespace App\Modules\Task\Services;

use App\Modules\User\Services\UserService;
use App\Modules\Task\Models\DrawTask;
use App\Modules\System\Services\DictionaryService;
use App\Modules\Task\Services\TaskService;
use App\Modules\Index\Models\Glucose;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DrawTaskService
{
    /**
     * 领取任务
     * param array $data
     */
    public static function addDrawTask($data=[]){
        return DrawTask::addDrawTask($data);
    }

    /**
     * 获取领取任务
     */
    public static function getDrawTask($task_code,$user_id){
        return DrawTask::getDrawTask($task_code,$user_id);
    }

    /**
     * 获取个人档案领取任务
     */
    public static function getHealthDrawTask($task_code,$user_id){
        return DrawTask::getHealthDrawTask($task_code,$user_id);
    }

    /**
     * 修改领取任务
     */
    public static function updateDrawTask($data){
        return DrawTask::updateDrawTask($data);
    }


    /**
     * 获取一个任务在一个时间段内领取的所有数据(定时脚本)
     */
    public static function oneTaskDrawAll($taskCode,$startTime,$endTime,$taskTimeStatus){
        //获取根据任务时间判断是否可以执行当前操作
        if ( !empty($taskTimeStatus) ) {
            $taskData = TaskService::getTask($taskCode,'code');
            if ( empty($taskData) ) {
                Log::info('任务获取失败');exit('任务获取失败');
            }
            $end_time = $taskData->end_time;
            $time = strtotime(date('Y-m-d '.$end_time.':00'));
            if ( time() > $time ) {
                $timeStatus = true;
            }
        }
        if ( !empty($taskTimeStatus) && empty($timeStatus) ) {
            exit('未到达时间');
        }
        //查询当天领取的所有数据
        $result = DrawTask::where('task_code',$taskCode)->where('created_at','>=',$startTime)->where('created_at','<=',$endTime)->where('status',1)->get()->toArray();
        Log::useDailyFiles(storage_path('logs/sugar/sugar.log'));
        if ( empty($result) ) {
            Log::info('当前没有任务领取数据');exit('当前没有任务领取数据');
        }
        //获取增副数值
        $amplitude = DictionaryService::getDictionary('amplitude');
        if ( empty($amplitude) ) {
            Log::info('增副数值配置项错误');
        }
        $date = date('Y-m-d H:i:s',time());
        $userArr = []; //记录完成的用户
        $amplitude = empty($amplitude) ? 3 : $amplitude->value;     //如果没有配置 给默认值3
        //遍历数据，获取用户值
        foreach ( $result as $key => $value ) {
            //获取用户血糖控制目标值
            $target_value = UserService::getTargetValue($value['user_id']);
            if ( empty($target_value) ) {
                Log::info('未获取到用户信息_用户id:'.$value['user_id']);
                continue;
            }
            $target_value = $target_value->target_value;
            //获取用户测量血糖达标率
            $glucoseCount = Glucose::where('user_id',$value['user_id'])->where('type',2)->where('test_at','>=',$startTime)->where('test_at','<=',$endTime)->count();
            $normalCount = Glucose::where('user_id',$value['user_id'])->where('type',2)->where('state',1)->where('test_at','>=',$startTime)->where('test_at','<=',$endTime)->count();
            $successRate = empty($glucoseCount) ? 0 : round($normalCount / $glucoseCount * 100,1);
            //修改领取任务状态，用户金币，用户控糖目标值
            DB::beginTransaction();
            try{
                $status = false;
                //判断用户是否完成任务 达标率大于控糖目标值 表示完成
                if ( $successRate >= $target_value ) {
                    //修改领取任务为已完成
                    $updateDrawTask = DrawTaskService::updateDrawTask(['id'=>$value['id'],'status'=>2]);
                    if( empty($updateDrawTask) ){
                        Log::info('领取任务修改失败_用户id'.$value['user_id']);
                        throw new \Exception('UPDATE_FAILURE');
                    }
                    //添加金币账单表
                    $coinInsertArr = [
                        'user_id'       => $value['user_id'],
                        'associated_id' => $value['id'],
                        'type'          => 3,
                        'created_at'    => $date,
                        'updated_at'    => $date,
                        'coin'          => $value['coin'],
                    ];
                    $coinInsert = DB::table('coin')->insert($coinInsertArr);
                    if ( empty($coinInsert) ) {
                        Log::info('金币账单数据添加失败_用户id:'.$value['user_id']);
                        throw new \Exception('UPDATE_FAILURE');
                    }
                    //修改用户金币
                    $updateUser = UserService::updateCoin($value['user_id'],$value['coin']);
                    if ( empty($updateUser) ) {
                        Log::info('用户金币修改失败_用户id:'.$value['user_id']);
                        throw new \Exception('UPDATE_FAILURE');
                    }
                    $status = true;
                }
                //修改用户的控糖目标值(达标率+增副数值，100为最高)
                $user_target_value =  round($successRate) + $amplitude;
                $user_target_value = $user_target_value > 100 ? 100 : $user_target_value;
                $save_target_value = UserService::updateUser(['id'=>$value['user_id'],'target_value'=>$user_target_value]);
                if ( empty($save_target_value) ) {
                    Log::info('用户控糖目标值修改失败_用户id:'.$value['user_id']);
                    throw new \Exception('UPDATE_FAILURE');
                }
                //记录完成的用户
                if ( !empty($status) ) {
                    array_push($userArr,$value['user_id']);
                }
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                continue;
            }
        }
        Log::info('执行完毕，当天完成用户为:'.implode(',',$userArr));
        exit('执行完毕，当天完成用户为:'.implode(',',$userArr));
    }
}